<template src="./resourceReg.html"></template>

<script>
import Bus from '@/utils/event_bus'
import GMenuItem from '@/components/common/g-menu-item'
import GButton from '@/components/common/g-button'
import ResourceRegList from './resourceReg-list'
import { appNameMapping } from '@/config/config'
import { appsInUse } from '@/config/config'
import {project as projectApi} from '@/api'
import {app as appApi} from '@/api'
import config from '@/config/newConfig.js'
import { setTimeout } from 'timers';
export default {
    name: 'ResourceReg',
    data () {
        return {
            // inputVisible: false,
            // inputValue: '',
            tagIndex:0,

            dialogLoading:false,

            dialogVisible: false,
            selected: 'public',
            selectedName:'公共资源',
            activeNames:"",
            activeNames2:"",
            formData:{
                title:"",
                group:"",
                department:[],
                comment:"",
                approvalFileList:[],
                spatialDataFileList:[]
            },
            departmentOptions:[],
            groupOptions:[],
            selectedUploadDataList:[],
            approvalFileList:[],
            spatialDataFileList:[],
            resClsList:[],
            appList: {
                name: '资源注册',
                submenu: [{
                        "name": "公共资源",
                        "key": "public",
                        "icon": "project2",
                        "count": 0
                    },
                    {
                        "name": "群组资源",
                        "key": "group",
                        "icon": "project2",
                        "count": 0
                    },
                    {
                        "name": "部门资源",
                        "key": "department",
                        "icon": "project2",
                        "count": 0
                    }
                ]
            },
            tableData:[],
            curPage:1,
            total:0,
            
            searchInput:"",
            resRegDetailDialogVisible:false,
            resRegDetail:{
                registOrder: {},
                resFrom0: {},
                resFrom1: {},
                attachFile:{}
            }
        }
    },
    activated () {
        //this.$emit( 'on-view-load' );
    },
    beforeRouteLeave ( to, from, next ) {
        // this.$destroy();
        next();
    },
    mounted () {
        // const vm = this;
        // Bus.$emit('on-submenu-change', '');
        // this.getMyApps();
        // await this.init();
        let path = this.$router.currentRoute.path;
        let paths = path.split('/');
        // await this.switchProjectType(paths[2]);
        // this.isMounted = true;
        
        this.$emit( 'on-view-load' );
        let name = this.getAppListByKey(paths[2]).name;
        Bus.$emit('on-submenu-change', name);
        
        //this.resourceRegStat();
        this.query();
        this.requestResCls();
       
    },
    methods: {
        getAppListByKey (key) {
            let apps = this.appList.submenu;
            let app = apps.filter((n) => {
                return n.key === key;
            });
            return app[0];
        },
        switchResourceRegType(key){
            if (key === this.selected) 
                return;
                this.selected = key;
            //console.log(key, this.selected);

            let apps = this.appList.submenu;
            let app = apps.find((n) => {
                return n.key === key;
            });
            this.selectedName = app.name;

            this.query();
        },
        handleLoadMore(page){
            if(this.curPage != page){
                this.curPage = page;      
                
                this.query('more');
            }
        },
        resourceRegStat(){
            let url = `${config.api}/resourceReg/query/count`;
            this.$root.$http.get(url).then((response)=>{
                //console.log(response);
                let resource = response.data.data.resource;
                this.appList.submenu.forEach((item)=>{
                    let element = resource.find((item2)=>{
                        return item2.name == item.name;
                    });
                    item.count = element.count;
                });
            });
        },
        handleSearchInputChange(){
            this.query();
        },
        query(type){
            if(type != 'more'){
                this.curPage = 1;
            }
            let params={
                ownerType: 0 //公共资源
            };
            if(this.searchInput!=""){
                params.title = this.searchInput;
            }
            if(this.selected=='group'){
               params.ownerType = 2;
            }else if(this.selected=='department'){
                params.ownerType = 1;
            }
            let url = `${config.api}/resourceReg/query/order?rows=8&page=${this.curPage}&order=DESC`;
            this.$root.$http.get(url, {
                params: params
            }).
            then((response)=>{
                // console.log(response);
                this.tableData = response.data.data;
                this.total = response.data.total;
            });
        },
        queryDetail(row){
            let url = `${config.api}/resourceReg/query/order/${row.regId}`;
            this.$root.$http.get(url)
            .then((response)=>{
                // console.log(response);
                let data = response.data.data;
                let resFrom1 = data.resFrom1;
                resFrom1.forEach((item)=>{
                    item.applyName = item.apply==0 ? '可申请':'不可申请';
                });
                this.resRegDetail = data;
                this.resRegDetailDialogVisible = true;
                
            });
        },
        deleteRow(index, rows) {
            this.$confirm('确定要删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //console.log(rows[index]);
                let url = `${config.api}/resourceReg/delete/order/${rows[index].regId}`;
                this.$root.$http.get(url).then((response)=>{
                    if(response.data.success){
                        rows.splice(index, 1);
                        this.$message({
                            type: 'success',
                            message: '删除成功！'
                        });
                    }
                });
                
            }).catch(() => {
                // this.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // });          
            });
        },
        showDialog(){
            this.dialogVisible = true;
        },
        handleCollapseChange(val){
            // console.log(val);
            
        },
        //审批材料上传
        handleApprovalRemove(file, fileList) {
            console.log(file, fileList);
        },
        handleApprovalPreview(file) {
            console.log(file);
        },
        handleApprovalChange(file, fileList){
            this.formData.approvalFileList = fileList;
        },
        //空间数据上传
        handleSpatialDataRemove(file, fileList) {
            console.log(file, fileList);
        },
        handleSpatialDataPreview(file) {
            console.log(file);
        },
        handleSpatialDataChange(file, fileList){
            this.formData.spatialDataFileList = fileList;
            this.selectedUploadDataList.push({
                name: file.name,
                resClsList: JSON.parse(JSON.stringify(this.resClsList)),
                metaData: {
                    resClsId: "",
                    coordinate: "",
                    apply: "",
                    tag: {
                        list:[],
                        saveTagInput: "saveTagInput_" + this.tagIndex++,
                        inputVisible: false,
                        inputValue: ""
                    }
                }
            });
        },
        handleSelectedDataClose(item){
            let index = this.selectedUploadDataList.indexOf(item);
            this.selectedUploadDataList.splice(index, 1);
        },
        //--书签--start
        handleClose(tag, tagItem) {
            tag.list.splice(tag.list.indexOf(tagItem), 1);
        },
        showInput(tag) {
            tag.inputVisible = true;

            // this.$nextTick(_ => {
            //     this.$refs[tag.saveTagInput].$refs.input.focus();
            // });
        },
        handleInputConfirm(tag) {
            let inputValue = tag.inputValue;
            if (inputValue) {
                tag.list.push(inputValue);
            }
            tag.inputVisible = false;
            tag.inputValue = '';
            
        },
        //--书签--end
        handleGroupFocus(){
            if(this.isFirstLoadGroup){
                return;
            }else{
                this.isFirstLoadGroup = true;
            }
            this.$root.$http.get(`${config.api}/user/group`)
            .then((response)=>{
                let data = response.data.data;
                data.forEach((item)=>{
                    this.groupOptions.push({
                        label: item.groupName,
                        value: item.groupId
                    });
                });
            });
        },
        handleDeptFocus(){
            if(this.isFirstLoadDept){
                return;
            }else{
                this.isFirstLoadDept = true;
            }
            this.$root.$http.get(`${config.api}/user/dept`)
            .then((response)=>{
                let deptList=[];
                this.traversalDept(response.data.data[0], deptList);
                // this.resourceAuthorityOptions[2].children = deptList;
                // this.traversalDept(response.data.data[0]);
                this.departmentOptions = deptList;
                
            });
        },
        traversalDept(tree, deptList){
            tree.value = tree.id;
            deptList.push({
                value: tree.value,
                label: tree.label
            });
            if(tree.children){
                tree.children.forEach((item)=>{
                    this.traversalDept(item, deptList);
                    // console.log(item);
                });
            }
        },
        // traversalDept(tree){
        //     tree.value = tree.id;
        //     if(!tree.children){
        //         delete tree.children;
        //         return;
        //     }else{
        //         tree.children.forEach((item)=>{
        //             this.traversalDept(item);
        //         });
        //     }
        // },
        requestResCls(){
            this.$root.$http.get(`${config.api}/resource/query/count/2`)
            .then((response)=>{
                //console.log(response);
                let list = response.data.data[2];
                list.forEach((item)=>{
                    this.resClsList.push({
                        label: item.name,
                        value: item.code
                    });
                });
                //console.log(this.resClsList);
                
            });
        },
        handleDialogSubmit(){
            // console.log(this.selectedUploadDataList);
            // console.log(this.formData);
            if(this.formData.title == ""){
                // this.$message.error('标题不能为空！');
                this.$message({
                    message: '标题不能为空！',
                    type: 'error'
                });
                return;
            }
            let ownerType = 0;
            if(this.selected == 'group'){
                ownerType = 2;
                if(this.formData.group == ""){
                    this.$message.error('请选择群组！');
                    return;
                }
            }else if(this.selected == 'department'){
                ownerType = 1;
                if(this.formData.department.length<=0){
                    this.$message.error('请选择部门！');
                    return;
                }
            }
            let flag = false;
            for(let index in this.selectedUploadDataList){
                let metaData = this.selectedUploadDataList[index].metaData;
                for(let key in metaData){
                    if(metaData[key] == "" && key != 'tag'){
                        flag = true;
                        break;
                    }
                    if(key == 'tag' && metaData[key].list.length>5){
                        flag = true;
                        break;
                    }
                }
                if(flag){
                    break;
                }
            }
            if(flag){
                this.$message.error(`上传的数据"分类"、"坐标系"、"权限"不能为空，
                                    并且标签个数不能超过5个！`);
                return;
            }

            if(this.formData.spatialDataFileList.length<=0){
                this.$message.error('请上传本地数据！');
                return;
            }
            if(this.formData.approvalFileList.length<=0){
                this.$message.error('请上传审批材料！');
                return;
            }
            let fd = new window.FormData();
            fd.append('title', this.formData.title);
            fd.append('ownerType', ownerType);
            let ownerId = "-99";
            if(this.formData.group != ""){
                ownerId = this.formData.group;
            }
            if(this.formData.department.length>0){
                ownerId = this.formData.department[this.formData.department.length-1];
            }
            fd.append('ownerId', ownerId);

            this.formData.spatialDataFileList.forEach((file)=>{
                fd.append('dataFile', file.raw);
            });
            this.formData.approvalFileList.forEach((file)=>{
                fd.append('attachFile', file.raw);
            });
            let metaDataList=[];
            this.selectedUploadDataList.forEach((item)=>{
                let metaData = item.metaData;
                metaDataList.push({
                    resFrom: "1",
                    fileName: item.name,
                    resClsId: metaData.resClsId,
                    coordinate: metaData.coordinate,
                    apply: metaData.apply,
                    label: metaData.tag.list.join(',')
                });
            });
            fd.append('metaDataList', JSON.stringify(metaDataList));
            fd.append('nt', this.formData.comment);
            
            this.$el.querySelector('.dialog-loading').style.display='block';
            this.dialogLoading = true;
            let url = `${config.api}/resourceReg/add`;
            this.$root.$http.post(url, fd,{
                headers:{
                    'Content-Type': 'multipart/form-data'
                }
            }).then((response)=>{
                // console.log(response);
                this.$el.querySelector('.dialog-loading').style.display='none';
                this.dialogLoading = false;
                this.dialogVisible=false;
                if(response.data.success){
                    this.$message.success('提交成功！');
                }else{
                    this.$message.error('提交失败！');
                }
            });
            

        },
        handleDialogClose(){
            // console.log('open...');
            this.dialogVisible = false;
            this.selectedUploadDataList=[];
            this.formData = {
                title: "",
                group: "",
                department:[],
                comment:"",
                approvalFileList:[],
                spatialDataFileList:[]
            };
            this.spatialDataFileList=[];
            this.approvalFileList=[];
            
        },
        handleDetailDialogClose(){
            this.resRegDetail={
                registOrder: {},
                resFrom0: {},
                resFrom1: {},
                attachFile:{}
            };
        }
    },
    components: {
        GMenuItem,
        GButton,
        ResourceRegList
    }
}
</script>

<style src="./resourceReg.scss" lang="scss" scoped></style>
